package a66weding.com.jiehuntong.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.home.BaseHomeActivity;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.Tools;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

public class WebViewActvity extends BaseHomeActivity implements View.OnClickListener {

    private TextView mTitleTv;
    private TextView mBackTv;
    private TextView rightTv;
    private WebView webView;
    private WebSettings settings;
    private Intent intent;
    private Context context;
    private String urlPath;
    private static File file;
    private boolean isMapView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);

        context = this;
        initView();
        initInfo();
        setData();
    }

    private void initInfo() {

        intent = getIntent();
        String title = intent.getStringExtra("title");
        urlPath = intent.getStringExtra("urlPath");
        boolean share = intent.getBooleanExtra("share", false);
        mTitleTv.setText(title);
        mBackTv.setText("");

        if(!TextUtils.isEmpty(title) && title.equals("婚礼举办地")){// 地图
            isMapView = true;
            webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
            webView.setWebChromeClient(new WebChromeClient(){
                @Override
                public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                    callback.invoke(origin,true,false);
                    super.onGeolocationPermissionsShowPrompt(origin, callback);
                }
            });
            File mCacheDir = CUtils.getApplication().getExternalCacheDir();
            if (null == mCacheDir)
                mCacheDir = CUtils.getApplication().getCacheDir();
            String dir = mCacheDir + "/baidudata";
            settings.setGeolocationDatabasePath(dir);
            settings.setDatabaseEnabled(true);
            settings.setGeolocationEnabled(true);
            settings.setAllowFileAccess(true);
            settings.setDomStorageEnabled(true);//允许DCOM
        }
        if (share) {
            rightTv.setVisibility(View.VISIBLE);
            rightTv.setText("分享");
            rightTv.setOnClickListener(this);
        } else {
            rightTv.setVisibility(View.GONE);
        }
    }

    private void initView() {
        mTitleTv = (TextView) findViewById(R.id.tv_header_title);
        mBackTv = (TextView) findViewById(R.id.tv_header_backcontent);
        rightTv = (TextView) findViewById(R.id.tv_header_function);
        findViewById(R.id.back_imageview).setOnClickListener(this);
        mBackTv.setOnClickListener(this);
        webView = (WebView) findViewById(R.id.marry_game_webView);
        settings = webView.getSettings();
        // 支持javascript
        settings.setJavaScriptEnabled(true);
        // 设置可以支持缩放
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(true);
        // 不显示缩放按钮
        settings.setDisplayZoomControls(false);
        // 扩大比例的缩放
        settings.setUseWideViewPort(true);
        // 自适应屏幕
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setLoadWithOverviewMode(true);
        // 不使用缓存，只从网络获取数据
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
//        if(Utils.checkNet(this)){
//            settings.setCacheMode(WebSettings.LOAD_DEFAULT);
//        } else {
//            settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
//        }


        webView.setWebViewClient(new WebViewClient() {// 回调网页加载的生命周期
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                if(isMapView){
                    Tools.showWaitDialog(WebViewActvity.this,"地图加载中...",true);
                }
//                Toast.makeText(context,"开始加载...",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                Tools.dismissWaitDialog();
//                Toast.makeText(context,"加载完成",Toast.LENGTH_SHORT).show();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if(url.startsWith("http") || url.startsWith("https")){
                    settings.setCacheMode(WebSettings.LOAD_DEFAULT);
                    if(!isMapView){
                        mBackTv.setText("关闭");
                    }
                    view.loadUrl(url);
                    return true;
                } else {
                    return super.shouldOverrideUrlLoading(view, url);
                }
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                Tools.dismissWaitDialog();
                if(!isMapView){
                    Toast.makeText(context, "加载失败，请重试", Toast.LENGTH_SHORT).show();
                }
            }
        });
        webView.setWebChromeClient(new WebChromeClient() );
    }

    private void setData() {
        webView.loadUrl(urlPath);
    }

    @Override
    protected void onPause() {
        Tools.dismissWaitDialog();
        super.onPause();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_header_backcontent:
                finish();
                break;
            case R.id.back_imageview:
                onBackPressed();
                break;
            case R.id.tv_header_function:
                showShare();
                break;
        }
    }

    /**
     * 一键分享
     */
    private void showShare() {
        String title = "结婚通";
        String description = "幸福从哪里开始，幸福从这里开始！";
        copyToSD(context);
//        getShareUtils();
        ShareSDK.initSDK(context);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        oks.setTitle(title);
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl(urlPath);
        // text是分享文本，所有平台都需要这个字段
        oks.setText(description);
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        String path = android.os.Environment.getExternalStorageDirectory().getPath() + "/" + "pic_share_0214.jpg";
        oks.setImagePath(path);//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl(urlPath);
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment(description);
        oks.setSiteUrl(urlPath);
        // 启动分享GUI
        oks.show(context);
    }

    /**
     * 把raw的图片存到SD卡上
     */
    public static void copyToSD(Context context) {
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            String path = android.os.Environment.getExternalStorageDirectory()
                    .getPath();
            String dbPathAndName = path + "/" + "pic_share_0214.jpg";
            file = new File(path);
            if (file.exists() == false) {
                file.mkdir();
            }
            File dbFile = new File(dbPathAndName);
            if (!dbFile.exists()) {
                is = context.getResources().openRawResource(
                        R.raw.pic_share);
                fos = new FileOutputStream(dbFile);
                byte[] buffer = new byte[8 * 1024];// 8K
                while (is.read(buffer) > 0)// >
                {
                    fos.write(buffer);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        if (webView.canGoBack() && !isMapView) {
            settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
            webView.goBack();//返回上一页面
        } else {
            finish();
        }
    }
}
